package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;


//员工
@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    //登录   当前项目的post和put请求都是使用请求体传参的 @RequestBody
    //@RequestBody只能标注在对象或者map之前
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        //1.接收参数
        String username = map.get("username");
        String password = map.get("password");

        //2.调用service进行登录
        ResultInfo resultInfo = employeeService.login(username, password);

        //3.如果登录成功,将employee对象写入session域对象
        Employee employee = (Employee) resultInfo.getData();
        session.setAttribute("SESSION_EMPLOYEE", employee);

        //4.结果返回前端
        return resultInfo;
    }

    //退出
    @PostMapping("/employee/logout")
    public ResultInfo logout() {

        //1.注销当前用户的session
        session.invalidate();//注销当前用户的session,不会动其他的session

        //2.返回成功标识
        return ResultInfo.success(null);
    }

    @GetMapping("/employee/find")
    public ResultInfo findByName(String name) {

        //根据name查询  不传name:查询所有  传name:模糊查询
        List<Employee> employeeList = employeeService.findByName(name);

        return ResultInfo.success(employeeList);
    }

    //新增员工
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee) {
        employeeService.save(employee);

        //返回成功标识
        return ResultInfo.success(null);
    }

    //查询员工
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }

    //修改员工
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee) {
        employeeService.update(employee);

        //返回成功标识
        return ResultInfo.success(null);
    }
}
